package com.ht.api.call.func.impl.fan;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;

import java.util.List;

import cn.hutool.json.JSONUtil;
import com.ht.api.bean.AjaxResult;
import com.ht.api.bean.LoginBean;
import com.ht.api.call.func.IFunctionCall;
import com.ht.api.db.Db;
import com.ht.api.db.Entity;
import com.ht.api.db.exception.HtException;
import com.ht.api.db.util.HtUtil;
import com.ht.api.open.OpenUtil;
import com.ht.api.service.FanService;
import com.ht.api.service.OfficialService;
import lombok.extern.slf4j.Slf4j;

/**
 * 渠道广告位状态变更函数
 */
@Slf4j
public class PositionChannelStatusFunctionCall implements IFunctionCall{

	/** 接口ID：创建永久二维码*/
	private static final long API_ID_OFFICIAL_ADD = 1910298760676773888L;

	@Override
	public String getName() {
		return "渠道广告位状态变更函数";
	}

	@Override
	public JSONObject execute(LoginBean me, JSONObject param, AjaxResult result) {
		int status = param.getInt("status");

		Entity position = Db.createSqlParser("position_channel").findById(me.getDataSource(), param.getStr("main_id"));

		Entity fanChannel = Entity.create("fan_channel");
		fanChannel.setMainId(position.getStr("channel_id"));
		if (status == 1) {
			String teamId = position.getStr("team_id");
			String inType = position.getStr("in_type");

			//查看接粉组是否有配置绑定数量，没有则不能正常启动
			String teamRelationTable = "fan_service_team_relation";
			if (inType.equals("wx_chat_way")) {
				teamRelationTable = "fan_chat_team_relation";
			} else if (inType.equals("kf_account")) {
				teamRelationTable = "fan_user_team_relation";
			} else if (inType.equals("wx_official_customer")) {
				teamRelationTable = "fan_official_user_team_relation";
			}

			long count = Db.createSqlParser(teamRelationTable)
					.where("team_id", teamId).where("status", 0).count(me.getDataSource());
			if (count == 0) {
				throw new HtException("接粉组绑定的数量为0，不能启用广告位！");
			}

			// 更新初始化状态和渠道的广告位数量
			Entity fanTeamBean = Db.createSqlParser("fan_team").findById(me.getDataSource(), teamId);

			if (position.getInt("init_status") == 0) {

				position.set("init_status", 2);
				// 创建配置信息
				if (inType.equals("wx_contact_way") || inType.equals("wx_chat_way") || inType.equals("wx_customer_link")) {
					List<String> ids = FanService.getRelIds(me.getDataSource(), teamId);
					String relationId = FanService.add(me.getDataSource(), fanTeamBean.getStr("appid"), position.getMainId(), position.getStr("name"),
							position.getStr("state"), position.getStr("in_type"), ids);

					position.set("relation_id", relationId);
				} else if (inType.equals("wx_official_customer") && StrUtil.isBlank(position.getStr("url"))) {
					String relationId = position.getStr("relation_id");

					JSONObject requestParam = JSONUtil.createObj();
					requestParam.set("action_name", "QR_LIMIT_STR_SCENE");
					requestParam.set("action_info.scene.scene_str", position.getStr("state"));

					String str = OpenUtil.call(relationId, API_ID_OFFICIAL_ADD, requestParam);

					JSONObject resultObj = JSONUtil.parseObj(str);

					String url = OfficialService.uploadQrcodeToAliyun(resultObj.getStr("ticket"));
					position.set("url", url);
				}

			} else {
				// 更新配置信息
				if (inType.equals("wx_contact_way") || inType.equals("wx_chat_way") || inType.equals("wx_customer_link")) {
					List<String> ids = FanService.getRelIds(me.getDataSource(), teamId);
					FanService.edit(me.getDataSource(), fanTeamBean.getStr("appid"), position.getMainId(), position.getStr("name"),
							position.getStr("state"), position.getStr("in_type"), ids);
				}

			}

			Entity fanTeam = Entity.create("fan_team");
			fanTeam.setMainId(teamId);
			fanTeam.set("normal_relation_cnt", 1);
			Db.insert(me.getDataSource(), fanTeam);

			fanChannel.set("normal_position_cnt", 1);

			HtUtil.createLog(me.getDataSource(), fanChannel.getMainId(), "启用["+fanChannel.getStr("name")+"]");


		} else { // 停用广告位
			if (position.getInt("status") == 1) {
				fanChannel.set("normal_position_cnt", -1);

				Entity fanTeam = Entity.create("fan_team");
				fanTeam.setMainId(position.getStr("team_id"));
				fanTeam.set("normal_relation_cnt", -1);
				Db.insert(me.getDataSource(), fanTeam);
			}

			HtUtil.createLog(me.getDataSource(), fanChannel.getMainId(), "停用["+fanChannel.getStr("name")+"]");
		}

		position.set("status", status);
		Db.insert(me.getDataSource(), position);
		Db.insert(me.getDataSource(), fanChannel);

		return null;
	}

}
